/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.ubc.cc.controller;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.apps.ubc.cc.model.SearchQueryModel;
import com.apps.utils.CourseSearchUtils;

public class SearchController extends HttpServlet {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
		String searchQuery = req.getParameter("q");
		String[] searchTerms;
		String dept = "";
		String course = "";
		String section = "";
		searchQuery = CourseSearchUtils.parseSearch(searchQuery);
		int countTerms = CourseSearchUtils.countTerms(searchQuery);
		if (countTerms > 0) {
			searchTerms = CourseSearchUtils.toWordArray(searchQuery);
			dept = CourseSearchUtils.findDepartment(searchTerms);
			course = CourseSearchUtils.findCourse(searchTerms);
			section = CourseSearchUtils.findSection(searchTerms);
		}
		try {
			SearchQueryModel sqm = new SearchQueryModel(dept, course, section);
			HttpSession s = req.getSession();
			s.setAttribute("result", sqm);
			req.getRequestDispatcher("/searchresults.jsp").forward(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
